import React, { PureComponent, useEffect, useState } from "react";
import { Layout, Menu, notification, Avatar, Col, Row, Dropdown, Select } from 'antd';
import { WindowsOutlined, SettingOutlined, UserOutlined, LogoutOutlined, EditOutlined } from '@ant-design/icons'
import router from 'umi/router';

import styles from './index.css';
import { Authority, Axios } from 'toolkit';
import routesConfig from '@/../config/routers';
import { DistrictItem, LoginInfo, Reslut } from '@/app';
import GlobalStore from '@/store';
import globalStoreData from '@/store';


const { Header, Content, Footer, Sider } = Layout;
const { SubMenu } = Menu;



interface MenuType {
    code: string,
    name: string,
    parentCode: string | null | undefined,
    path: string | null | undefined,
    isDirectory: boolean,
    order: number,
    children: MenuType[],
}

interface OptionsType {
    label: string,
    value: string
}


class MenuLayout extends PureComponent<any, any>{


    constructor(props: any) {
        super(props);
    }

    state = {
        menuList: []
    }


    componentDidMount() {
        // let userCode = store.userCode;
        let userCode = GlobalStore.getStore('LoginInfo').userCode;
        if (userCode) {
            Axios.get(`/queryMenuList?userCode=${userCode}`).then(response => {
                let reslut = response.data;
                if (!reslut.succeed) {
                    notification.error({
                        message: '获取菜单错误',
                        description: reslut.message,
                    });
                    return;
                }

                let menuList: MenuType[] = reslut.data.map((item: any) => {
                    let menu: MenuType = {
                        code: item.code,
                        name: item.name,
                        parentCode: item.parentCode,
                        path: item.path,
                        isDirectory: item.isDirectory,
                        order: item.order,
                        children: []
                    }
                    return menu;
                });

                this.setState({
                    menuList
                });

            }).catch(error => {
                console.error(error);
                notification.error({
                    message: '系统错误',
                    description: error.message,
                });
            });

        }

    }

    render() {

        let menu: MenuType[] = this.state.menuList.filter((value: MenuType) => !value.parentCode);
        menu = this.doRecursionMenuData(menu);

        let layout = this.doRecursionLayout(menu);

        return (
            <Menu mode="inline" onClick={this.onClickMenu.bind(this)}>
                {layout}
            </Menu>
        )


    }

    /**
     * 点击菜单
     * @param value 
     */
    onClickMenu(value: any) {

        // let findRoute = this.props.routes.find((item: { path: React.ReactText; }) => item.path === value.key)
        if (this.doFindRoute(value.key)) {
            router.push(value.key);
        }
        else {
            router.push("/404")
        }


    }

    /**
     * 判断路由地址
     * @param path 
     */
    doFindRoute(path: String) {

        return doRecursionFind(routesConfig, path);

        function doRecursionFind(routes: any[], path: String) {
            return routes.some(item => {
                let isFind = false;
                if (item.routes) {
                    isFind = doRecursionFind(item.routes, path)
                }
                if (isFind) {
                    return true;
                }
                if (item.path === path) {
                    return true;
                }

            });
        }
    }

    /**
     * 递归组织菜单渲染
     * @param menu 
     */
    doRecursionLayout(menu: MenuType[]) {

        return menu.map((menuItem: MenuType) => {

            let layout;
            if (menuItem.isDirectory) {
                let childrenMenu = this.doRecursionLayout(menuItem.children);
                layout = (<SubMenu key={menuItem.code} title={menuItem.name} >
                    {childrenMenu}
                </SubMenu>);
            }
            else {
                layout = (<Menu.Item key={menuItem.path} title={menuItem.name}>{menuItem.name}</Menu.Item>)
            }

            return layout;
        })

    }

    /**
     * 递归组织菜单数据
     * @param menu 
     */
    doRecursionMenuData(menu: MenuType[]) {

        menu = menu.map((menuItem: MenuType) => {

            let children: MenuType[] = this.state.menuList.filter((value: MenuType) => value.parentCode === menuItem.code)
            menuItem.children = children.sort((a, b) => a.order - b.order);

            this.doRecursionMenuData(menuItem.children);

            return menuItem;
        });
        return menu.sort((a, b) => a.order - b.order);
    }
}


/**
 * 基本布局模版
 * @param props 
 */
const HomeLayout: React.FC = (props: any) => {

    const [districtCode, setDistrictCode] = useState<string>();
    const [options, setOptions] = useState<OptionsType[]>();
    const [isDisabled, setIsDisabled] = useState<boolean>(false);

    const userMenu = (<Menu onClick={(value) => onUserMenuClick(value)}>
        <Menu.Item icon={<EditOutlined />} key="/userinfo" >用户信息</Menu.Item>
        <Menu.Item icon={<LogoutOutlined />} key="/logout">注销退出</Menu.Item>
    </Menu>)

    const onUserMenuClick = (value: any) => {

        if (value.key === "/logout") {
            Authority.delToken();
            sessionStorage.clear();
            router.push("/");
            return;
        }
        router.push(value.key);
    }

    useEffect(() => {
        if (!districtCode) {
            return;
        }
        GlobalStore.setStore('districtCode', districtCode);

        Axios.post('/sysEnumList', undefined, {
            headers: { "DISTRICT_CODE": districtCode }
        }).then(response => {
            let reslut: Reslut = response.data;
            if (!reslut.succeed) {
                notification.warn({
                    message: '获取系统数据错误',
                    description: reslut.message,
                });
                return;
            }
            globalStoreData.setStore('SysEnumList', JSON.stringify(reslut.data));

        }).catch(error => {
            console.error(error);
        });
    }, [districtCode])

    useEffect(() => {

        let tmpLoginInfo: LoginInfo = GlobalStore.getStore('LoginInfo') as LoginInfo;

        Axios.post('/allDistrictList').then(response => {
            let reslut: Reslut = response.data;
            if (!reslut.succeed) {
                notification.warn({
                    message: '获取区划错误',
                    description: reslut.message,
                });
                return;
            }
            let districts: DistrictItem[] = reslut.data as DistrictItem[];

            let tmpOptions: OptionsType[] = districts.map((item: DistrictItem) => {
                return {
                    label: item.name,
                    value: item.code
                }
            });
            setOptions(tmpOptions);
            let index = tmpOptions.findIndex(item => item.value === tmpLoginInfo.districtCode);
            if (index > -1) {
                setDistrictCode(tmpOptions[index].value);
            }
            setIsDisabled((!tmpLoginInfo.districtCode || tmpLoginInfo.districtCode !== '1111') ? true : false);

        }).catch(error => {
            console.error(error);
        })

    }, [])


    return (
        <div className={styles.normal}>
            <Layout>
                <Sider theme="light" className={styles.sider} >
                    <h1 className={styles.logo}>电子健康卡管理平台</h1>
                    <MenuLayout></MenuLayout>
                </Sider>
                <Layout>
                    <Header style={{ backgroundColor: 'rgb(34, 149, 238)' }}  >
                        <Row >
                            <Col span={20}>

                            </Col>
                            <Col span={3}>
                                <Select style={{ width: "140px" }} size="middle" value={districtCode} disabled={isDisabled} options={options} onSelect={(value) => {
                                    setDistrictCode(value);
                                }} ></Select>
                            </Col>
                            <Col push={1} span={1} >
                                <Dropdown overlay={userMenu} >
                                    <Avatar style={{ alignSelf: 'center' }} icon={<UserOutlined />} ></Avatar>
                                </Dropdown>
                            </Col>
                        </Row>
                    </Header >
                    <Content>
                        {props.children}
                    </Content>
                    <Footer className={styles.footer}>
                        电子健康卡管理平台 ©2020 成都新医线科技有限公司版权所有
                    </Footer>
                </Layout>
            </Layout>
        </div >
    );

}


export default HomeLayout;